﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Testing
{
	public class TreeNode
	{
		private int value;
		private List<TreeNode> children;

		public TreeNode(int value)
		{
			this.value = value;
			this.children = new List<TreeNode>();
		}

		public int Value
		{
			get { return this.value; }
			set { this.value = value; }
		}

		public int ChildrenCount
		{
			get { return children.Count; }
		}

		public void AddChild(TreeNode child)
		{
			this.children.Add(child);
		}

		public TreeNode GetChild(int index)
		{
			return this.children[index];
		}
	}

	class Program
	{
		static void Main(string[] args)
		{
			Random rnd = new Random();
			int treesCount = rnd.Next(1, 1000);

			TreeNode root = new TreeNode(rnd.Next(1, 20));

			InsertTree(root, 1, treesCount, rnd);

			StringBuilder sb = new StringBuilder();
			PrintTree(root, sb);

			Console.WriteLine(sb.ToString());
		}

		private static bool InsertTree(TreeNode root, int counter, int max, Random rnd)
		{
			int childsCount = rnd.Next(0, 6);

			for (int i = 0; i < childsCount; i++)
			{
				TreeNode node = new TreeNode(rnd.Next(1, 20));
				root.AddChild(node);
				counter++;
				if (counter >= max)
				{
					return true;
				}
				if (InsertTree(node, counter, max, rnd))
				{
					return true;
				}
			}

			return false;
		}

		private static void PrintTree(TreeNode root, StringBuilder sb)
		{
			if (root.ChildrenCount > 0)
			{
				sb.Append('(');
				sb.Append(root.Value);
				sb.Append("->");
				for (int i = 0; i < root.ChildrenCount; i++)
				{
					PrintTree(root.GetChild(i), sb);
					if (i < root.ChildrenCount -1)
					{
						sb.Append(',');
					}
				}
				sb.Append(')');
			}
			else
			{
				sb.Append(root.Value);
			}
		}
	}
}
